
package at.fhj.ase.clientarch.server.util;

import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author cja, sfe | www.fh-joanneum.at | Client Architectures and Design
 */
public final class JPAUtil {
  /** Describes the default persistence type which is <code>cpustatistics_HSQL</code> and is contained in <code>persistence.xml</code> */
  public final static String DEFAULT_PERSISTENCE_TYPE = "cpustatistics_HSQL";

  private static EntityManagerFactory emFactory;
  private static Logger logger = LoggerFactory.getLogger(JPAUtil.class.getName());

  private JPAUtil() {
    throw new AssertionError("JPAUtil: Util classes are not intended/allowed to be instantiated!");
  }

  public static EntityManagerFactory getEmFactory() {
    if (emFactory == null) {
      createDefaultSessionFactory();
    }
    return emFactory;
  }

  /** Shuts down the <code>EntityManagerFactory</code> and closes caches and connection pools */
  public static void shutdown() {
    getEmFactory().close();
  }

  /**
   * Creates a session factory for the provided {@link String} instance
   * 
   * @param persistenceType the persictence type for what a session shall be created for.
   */
  public static void createSessionFactory(final String persistenceType) {
    createNamedSessionFactory(persistenceType);
  }

  /** Creates a session factory with the default persistence type {@link #DEFAULT_PERSISTENCE_TYPE} */
  public static void createDefaultSessionFactory() {
    createNamedSessionFactory(DEFAULT_PERSISTENCE_TYPE);
  }

  private static void createNamedSessionFactory(final String persistenceType) {
    try {
      emFactory = Persistence.createEntityManagerFactory(persistenceType);
    } catch (Throwable t) {
      logger.error("Could not instantiate entityManagerFactory due to following reason: " + t);
      throw new ExceptionInInitializerError(t);
    }
  }
}
